package com.badshun.ojs;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OJSLexer {
    private ArrayList<String> scriptContentList;
    private OJSRuntime runtime;

    private static final String[] regexRules = {
            "^\\s*var\\s+(\\w+)\\s*=\\s*(.*?)\\s*$", // var name = value
            "^\\s*$", // empty line
            // "^$"
    };

    private static final String[] matchTypes = {
            "VAR",
            "EL"
    };

    public OJSLexer(ArrayList<String> scriptContentList, OJSRuntime runtime) {
        this.scriptContentList = scriptContentList;
        this.runtime = runtime;

        matchLine();
    }

    private void matchLine() {
        for (int i = 0; i < scriptContentList.size(); i++) {
            for (int j = 0; j < regexRules.length; j++) {
                Matcher matcher = getMatcher(scriptContentList.get(i), regexRules[j]);

                if (matcher.find()) {
                    // match type
                    if (matchTypes[j].equals("VAR")) { // group count should equals 2
                        String varName = matcher.group(1);
                        String varValue = matcher.group(2);

                        defineVar(varName, varValue);

                    } else if (matchTypes[j].equals("EL")) {
                        // do nothing
                    }
                }
            }
        }
    }

    private void defineVar(String name, String value) {
        if (runtime.getInMemory(OJSObject.TYPE.VAR, name) == null) {
            runtime.applyForMemory(new OJSVar(name, value, runtime));
        } else {
            // throws exception
            // name is existed
            System.err.println("var name [" + name + "] is existed");
        }
    }

    private Matcher getMatcher(String content, String regexRule) {
        Pattern pattern = Pattern.compile(regexRule);
        Matcher matcher = pattern.matcher(content);

        return matcher;
    }
}
